package com.rc.saas.tenant.init;

import com.alibaba.fastjson.JSON;
import com.rc.saas.tenant.common.constant.SessionConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

/**
 * APP配置信息缓存到Redis
 * Created by sven on 2019/12/7
 */
//@Component
public class RedisTenantConfigurationLoader {
    private static Logger logger = LogManager.getLogger(RedisTenantConfigurationLoader.class);

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据originalid获取配置
     * @param tenantCode
     * @return
     */
    public RedisTenantConfig get(String tenantCode) {
        String configuration = (String) redisTemplate.opsForValue().get(MessageFormat.format(SessionConstants.CACHE_TENANTCONFIG_TEMP, tenantCode));
        logger.warn("读取REDIS RedisWxConfiguration:{}", configuration);

        if (StringUtils.isNotBlank(configuration)) {
            return JSON.parseObject(configuration, RedisTenantConfig.class);
        } else {
            return null;
        }
    }

    /**
     * 保存到Redis中
     * @param redisAppConfig
     */
    public void set(RedisTenantConfig redisAppConfig) {
        logger.warn("保存configuration信息 [{}]", redisAppConfig.toString());

        //if (null == accessToken || StringUtils.isEmpty(accessToken.getAccess_token())) {
        //    throw new IllegalStateException("access_token is null or empty");
        //}
        //if (accessToken.getCreate_time() <= 0) {
        //    throw new IllegalStateException("createtime can not be zero");
        //}
        //if (accessToken.isExprexpired()) {
        //    throw new IllegalStateException("access_token is exprexpired");
        //}

        String configuration = JSON.toJSONString(redisAppConfig);
        logger.warn("configuration [{}]", configuration);

        //有效期365天
        redisTemplate.opsForValue().set(MessageFormat.format(SessionConstants.CACHE_TENANTCONFIG_TEMP, redisAppConfig.getTenantCode()), configuration, 365, TimeUnit.DAYS);
        logger.info("将配置信息保存到Redis缓存中:{}", redisAppConfig);
    }
}
